package com.emuporium.gymrat.server.program;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emuporium.gymrat.server.data.ProgramDB;

@SuppressWarnings("serial")
public class ProgramUpdateSubmitServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		int programId = new Integer(request.getParameter("programid"));
		String name = request.getParameter("name");
		String description = request.getParameter("description");
		String author = request.getParameter("author");
		Boolean shared = null;
		String[] routinesParam = request.getParameterValues("routineid");
		String[] notesParam = request.getParameterValues("note");
		String[] deleteParam = request.getParameterValues("deletebox");
		ArrayList<Integer> deleteList = new ArrayList<Integer>();

		if(deleteParam != null){
			for(String s : deleteParam){
				deleteList.add(new Integer(s));
				ProgramDB.removeRoutine(programId,new Integer(s));
			}
		}
		
		for(int i = 0; i < routinesParam.length ; i++) {
			int routineId = new Integer(routinesParam[i]);
			
			if(!deleteList.contains(routineId)){
				ProgramDB.updateRoutine(programId, routineId, notesParam[i]);
			}
		}
		
		if(request.getParameter("share") != null)
			shared = true;
		else
			shared = false;
		
		ProgramDB.update(programId, name, description, author, shared);
		
		request.setAttribute("redirecturl", "/program/list");
		String url = "/includes/redirect.jsp";
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}
}
